package com.cn.load.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.cn.load.utils.UploadUtils;



public class Cservlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		
		ServletFileUpload upload = new ServletFileUpload(factory);

		if(!upload.isMultipartContent(request)){
			throw new RuntimeException("当前不是多段式提交!");
		}
		upload.setHeaderEncoding("UTF-8");
		try {
			List<FileItem> list = upload.parseRequest(request);
			if (list!=null) {
				for (FileItem fi : list) {
					if (fi.isFormField()) {
						System.out.println("key:" + fi.getFieldName());
						System.out.println("value:" + fi.getString("UTF-8"));
					} else {
						System.out.println("文件提交的键：" + fi.getFieldName());
						System.out.println("文件原始名称：" + fi.getName());
						System.out.println("文件的mime类型：" + fi.getContentType());
						System.out.println("文件长度：" + fi.getSize());
						
						String uuid = UUID.randomUUID().toString();
						String dirpath = getServletContext().getRealPath("/uploadFile");
						String datepath =  UploadUtils.getDatePath(new Date());
						File test = new File(dirpath+datepath);
						if(!test.exists()){
							test.mkdirs();
						}
						
						InputStream is = fi.getInputStream();
						FileOutputStream fos = new FileOutputStream(dirpath+datepath+uuid);
						System.out.println(dirpath+datepath+uuid);
						IOUtils.copy(is, fos);
						is.close();
						fos.close();
						fi.delete();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			throw new RuntimeException("解析失败！");
		}
	}

}
